import ProgressHUD
import SafariServices
import UIKit

class WelcomeViewController: UIViewController {

  // MARK: - UI Components
  private let logoImageView: UIImageView = {
    let imageView = UIImageView()
    imageView.translatesAutoresizingMaskIntoConstraints = false
    imageView.contentMode = .scaleAspectFit
    imageView.backgroundColor = .clear  // 临时背景色，等待实际logo
    imageView.image = UIImage(named: "login_image_logo")
    return imageView
  }()

  private let titleLabel: UILabel = {
    let label = UILabel()
    label.translatesAutoresizingMaskIntoConstraints = false
    label.text = "爆单键盘"
    label.textAlignment = .center
    label.font = .systemFont(ofSize: 24, weight: .medium)
    return label
  }()

  private lazy var wechatLoginButton: UIButton = {
    let button = UIButton(type: .system)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitle("绑定爆单王账号", for: .normal)
    button.setTitleColor(.white, for: .normal)
    button.titleLabel?.font = .systemFont(ofSize: 18)
    button.backgroundColor = UIColor(red: 255 / 255, green: 99 / 255, blue: 31 / 255, alpha: 1)
    button.layer.cornerRadius = 22
    button.addTarget(self, action: #selector(wechatLoginTapped), for: .touchUpInside)
    return button
  }()

  private lazy var protocolsLabel: UITextView = {
    let textView = UITextView()
    textView.translatesAutoresizingMaskIntoConstraints = false
    textView.backgroundColor = .clear
    textView.isEditable = false
    textView.isScrollEnabled = false
    textView.textAlignment = .center
    textView.textContainerInset = .zero
    textView.textContainer.lineFragmentPadding = 0

    let fullText = "查看并同意《使用协议》、《隐私政策》"
    let attributedString = NSMutableAttributedString(string: fullText)
    let protocolRange = (fullText as NSString).range(of: "《使用协议》")
    let privacyRange = (fullText as NSString).range(of: "《隐私政策》")

    attributedString.addAttribute(
      .link, value: "https://bdw-storage.zmeng123.com/bdw/bdsInput/bds_use.html",
      range: protocolRange)
    attributedString.addAttribute(
      .link, value: "https://bdw-storage.zmeng123.com/bdw/bdsInput/bds_provacy.html",
      range: privacyRange)
    attributedString.addAttribute(
      .foregroundColor, value: UIColor.gray, range: NSMakeRange(0, fullText.count))
    attributedString.addAttribute(
      .font, value: UIFont.systemFont(ofSize: 14), range: NSMakeRange(0, fullText.count))

    textView.attributedText = attributedString
    return textView
  }()

  private lazy var protocolCheckButton: UIButton = {
    let button = UIButton(type: .custom)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setImage(UIImage(systemName: "square"), for: .normal)
    button.setImage(UIImage(systemName: "checkmark.square.fill"), for: .selected)
    button.tintColor = UIColor.systemOrange
    button.addTarget(self, action: #selector(protocolCheckToggled), for: .touchUpInside)
    return button
  }()

  private lazy var protocolStackView: UIStackView = {
    let stack = UIStackView(arrangedSubviews: [protocolCheckButton, protocolsLabel])
    stack.axis = .horizontal
    stack.spacing = 8
    stack.alignment = .center
    stack.translatesAutoresizingMaskIntoConstraints = false
    return stack
  }()

  private lazy var passwordLoginButton: UIButton = {
    let button = UIButton(type: .system)
    button.translatesAutoresizingMaskIntoConstraints = false
    button.setTitle("账号密码登录", for: .normal)
    button.setTitleColor(.gray, for: .normal)
    button.titleLabel?.font = .systemFont(ofSize: 14)
    button.addTarget(self, action: #selector(loginWithAccount), for: .touchUpInside)
    return button
  }()

  // MARK: - Lifecycle
  override func viewDidLoad() {
    super.viewDidLoad()
    setupUI()
    WXApiManager.shared.delegate = WXApiHandler.shared
    WXApiHandler.shared.onWXLoginSuccess = { [weak self] unionId in
      self?.loginAction(unionId)
    }
  }

  // MARK: - UI Setup
  private func setupUI() {
    view.backgroundColor = .white

    view.addSubview(logoImageView)
    view.addSubview(titleLabel)
    view.addSubview(wechatLoginButton)
    view.addSubview(passwordLoginButton)
    view.addSubview(protocolStackView)

    protocolsLabel.delegate = self

    NSLayoutConstraint.activate([
      logoImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
      logoImageView.topAnchor.constraint(
        equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 120),
      logoImageView.widthAnchor.constraint(equalToConstant: 100),
      logoImageView.heightAnchor.constraint(equalToConstant: 100),

      titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
      titleLabel.topAnchor.constraint(equalTo: logoImageView.bottomAnchor, constant: 20),

      wechatLoginButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
      wechatLoginButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 30),
      wechatLoginButton.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -30),
      wechatLoginButton.heightAnchor.constraint(equalToConstant: 44),
      wechatLoginButton.bottomAnchor.constraint(
        equalTo: passwordLoginButton.topAnchor, constant: -150),

      protocolStackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
      protocolStackView.topAnchor.constraint(equalTo: wechatLoginButton.bottomAnchor, constant: 16),

      passwordLoginButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
      passwordLoginButton.bottomAnchor.constraint(
        equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20),
    ])
  }

  // MARK: - Actions
  @objc private func wechatLoginTapped() {
    if !checkAgreeProtocol() { return }
    // 微信登录逻辑
    let launchMiniProgramReq = WXLaunchMiniProgramReq()
    launchMiniProgramReq.userName = "gh_b785c81d6ada"  //拉起的小程序的原始id，gh_xxx
    launchMiniProgramReq.path = "/pages/appMiddlePage/appMiddlePage"
    ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
    launchMiniProgramReq.miniProgramType = WXMiniProgramType.release  //拉起小程序的类型
    //        return  /*[WXApi sendReq:launchMiniProgramReq];*/
    WXApi.send(launchMiniProgramReq)
  }

  @objc private func loginWithAccount() {
    if !checkAgreeProtocol() { return }
    let loginVC = LoginViewController()
    let navigationController = UINavigationController(rootViewController: loginVC)
    // 设置模态展示样式为全屏
    navigationController.modalPresentationStyle = .fullScreen
    present(navigationController, animated: true)
  }

  @objc private func protocolCheckToggled() {
    protocolCheckButton.isSelected.toggle()
  }

  private func checkAgreeProtocol() -> Bool {
    if protocolCheckButton.isSelected {
      return true
    }

    // Shake animation
    let animation = CAKeyframeAnimation(keyPath: "transform.translation.x")
    animation.timingFunction = CAMediaTimingFunction(name: .linear)
    animation.duration = 0.4
    animation.values = [-10, 10, -8, 8, -5, 5, 0]
    protocolStackView.layer.add(animation, forKey: "shake")

    return false
  }
}

extension WelcomeViewController {
  func managerDidRecvMessageResponse(_ response: SendMessageToWXResp) {
    print("没用")
  }

  func managerDidRecvAuthResponse(_ response: SendAuthResp) {
    print("没用")
  }

  func managerDidRecvAddCardResponse(_ response: AddCardToWXCardPackageResp) {
    print("没用")
  }

  func managerDidRecvChooseCardResponse(_ response: WXChooseCardResp) {
    print("没用")
  }

  func managerDidRecvChooseInvoiceResponse(_ response: WXChooseInvoiceResp) {
    print("没用")
  }

  func managerDidRecvSubscribeMsgResponse(_ response: WXSubscribeMsgResp) {
    print("没用")
  }

  func managerDidRecvInvoiceAuthInsertResponse(_ response: WXInvoiceAuthInsertResp) {
    print("没用")
  }

  func managerDidRecvShowMessageReq(_ request: ShowMessageFromWXReq) {
    print("没用")
  }

  func managerDidRecvLaunchFromWXReq(_ request: LaunchFromWXReq) {
    print("没用")
  }
}

extension WelcomeViewController {
  //    func managerDidRecvLaunchMiniProgram(_ response: WXLaunchMiniProgramResp) {
  //        guard let unionId = response.extMsg else {
  //            ProgressHUD.failed("授权失败")
  //            return
  //        }
  //        loginAction(unionId)
  //    }

  func loginAction(_ unionId: String) {
    let idfv = UIDevice.current.identifierForVendor?.uuidString
    let body = [
      "unionId": unionId,
      "deviceId": idfv,
      "deviceType": "iOS",
    ]

    HttpClient.shared.postWithAutoHUD(endpoint: "/login", body: body as [String: Any]) {
      (userData: UserData?) in
      guard let userData = userData else {
        ProgressHUD.failed("获取用户信息失败！")
        return
      }
      // 🎉 登录成功，保存 Token
      if let token = userData.token, let userName = userData.userName {
        UserDefaults.baodan.set(token, forKey: UserDefaults.tokenKey)
        UserDefaults.baodan.set(userName, forKey: UserDefaults.userNameKey)
        UserDefaults.baoDan.saveUserDataToUserDefaults(userData: userData)

        print("✅ 登录成功，用户名：\(userName)")

        if let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate
          as? SceneDelegate
        {
          let window = sceneDelegate.window

          let mainTabBarController = MainTabBarController()

          // 切换根视图控制器
          UIView.transition(
            with: window!, duration: 0.5, options: .transitionCrossDissolve,
            animations: {
              window?.rootViewController = mainTabBarController  // 登录成功后，切换到主页面
            })
        }
      } else {
        ProgressHUD.failed("登录失败：未获取到用户信息")
      }
    }
  }
}

// MARK: - UITextViewDelegate
extension WelcomeViewController: UITextViewDelegate {
  func textView(
    _ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange,
    interaction: UITextItemInteraction
  ) -> Bool {
    let safariVC = SFSafariViewController(url: URL)
    present(safariVC, animated: true)
    return false
  }
}
